/**
 * ButtonOnTouchListener.java
 *
 * Created by Andrew Moss on 29 May 2011
 *
 */
package com.mossdev.android.moteapp.listeners;

import com.mossdev.android.moteapp.Config;
import com.mossdev.android.moteapp.MoteApp;
import com.mossdev.android.moteapp.comms.ServerConnectionException;

import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;

/**
 * This class handles touch events within a button. If it is a down event,
 * the given down command is sent. If it is an up event, the given up command
 * is sent.
 * 
 * @implements OnTouchListener
 * @author Andrew Moss
 *
 */
public class ButtonOnTouchListener implements OnTouchListener {

	private String up_cmd;
	private String down_cmd;

	/**
	 * Construct an object of this class where the button up and down
	 * commands are as provided.
	 * @param up
	 * @param down
	 */
	public ButtonOnTouchListener(String up, String down) {
		this.up_cmd = up;
		this.down_cmd = down;
	}


	@Override
	/**
	 * Called when touch event occurs on view this is used as a listener for.
	 */
	public boolean onTouch(View v, MotionEvent event) {

		// Get the type of action driving the callback
		switch (event.getAction()) {
		
		//Send down command on down event
		case (MotionEvent.ACTION_POINTER_DOWN):
		case (MotionEvent.ACTION_DOWN): {
			try {
				MoteApp.servercomms.sendCommand(this.down_cmd);
			} catch (ServerConnectionException e) {
				Log.e(Config.LogTag, e.err_msg);
			}
			break;
		}
		
		case (MotionEvent.ACTION_POINTER_UP):
		case (MotionEvent.ACTION_UP): {
			try {
				MoteApp.servercomms.sendCommand(this.up_cmd);
			} catch (ServerConnectionException e) {
				Log.e(Config.LogTag, e.err_msg);
			}
			break;
		}
		
		default: {
			//do nothing
			break;
		}
		}
			
		
		return true;
	}

}
